//
//  GetImgsView.m
//  夺宝吧
//
//  Created by xiaocai on 15/7/29.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "GetImgsView.h"
#import "AFHTTPRequestOperationManager.h"
#import "ZYQAssetPickerController.h"
#import "PostImageView.h"
#import "ShowOrderVC.h"
//上传图片
#define POST_IMG_URL @"/api/ApiUser/uploadShareOrderImg"
//上传晒单信息
#define POST_SAIDAN_URL @"/api/ApiUser/shareShoppingOrder"
//晒单最新记录
#define MOREN_URL @"/api/ApiUser/getLatestShareOrder"
//定义最大选择图片的个数
#define MAXNUM 8
@interface GetImgsView ()<UITextViewDelegate,ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate>
{
    __weak IBOutlet UILabel *titleLab;
    __weak IBOutlet UITextField *titletext;
    __weak IBOutlet UITextView *descText;
    __weak IBOutlet UIButton *imgBtn;
    //下方背景
    __weak IBOutlet UIView *bottomBg;
    __weak IBOutlet UILabel *jifenLab;
    __weak IBOutlet UIButton *commitbtn;
    __weak IBOutlet UIButton *selectBtn;
    __weak IBOutlet UILabel *wuliuLab;
    __weak IBOutlet UILabel *codeLab;
    
    //要隐藏的
    __weak IBOutlet UILabel *yc1;
    __weak IBOutlet UILabel *yc2;
    __weak IBOutlet UILabel *yc3;
    UIView *fenge;
    
    //当前点击的图片
    PostImageView *pressedImg;
    //记录当前上传的相片
    NSInteger currentImg;
    //请求一次标志
    BOOL oneFlag;
}
//选择所得的图片数组
@property (nonatomic, strong) NSMutableArray *assets;
//默认图片要上传的链接
@property (nonatomic,strong)NSMutableArray *morenPostPaths;
//返回的图片链接数组
@property (nonatomic,strong) NSMutableArray *imgPaths;
//装图片空间的数组
@property (nonatomic,strong) NSMutableArray *imgViews;
//默认图片数组
@property (nonatomic,strong) NSMutableArray *morenImgs;
@end
@implementation GetImgsView

- (void)awakeFromNib{
    selectBtn.center = CGPointMake(selectBtn.center.x, jifenLab.center.y*AUTOY);
    descText.layer.cornerRadius = 4;
    descText.layer.masksToBounds = YES;
    descText.layer.borderColor = [UIColor lightGrayColor].CGColor;
    descText.layer.borderWidth = 0.5;
    descText.delegate = self;
    descText.backgroundColor = [UIColor whiteColor];
    bottomBg.backgroundColor = [UIColor whiteColor];
    [selectBtn setImage:[UIImage imageNamed:@"icon_checkbox_press"] forState:UIControlStateSelected];
    selectBtn.selected = YES;
    selectBtn.frame = CGRectMake(selectBtn.frame.origin.x, CGRectGetMinY(jifenLab.frame), selectBtn.frame.size.width, selectBtn.frame.size.height);
    fenge = [WYPublic getFenGexian:10 :CGRectGetMaxY(jifenLab.frame)+10*AUTOY :WYMWITH - 20 :0.5];
    [bottomBg addSubview:fenge];
    commitbtn.layer.cornerRadius = 2;
    commitbtn.layer.masksToBounds = YES;
    commitbtn.backgroundColor = QBB_RED_COLOR;
    imgBtn.frame = CGRectMake(imgBtn.frame.origin.x, imgBtn.frame.origin.y, imgBtn.frame.size.width*AUTOX, imgBtn.frame.size.height*AUTOX);
    //键盘
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeKeyBoard)];
    [self addGestureRecognizer:tap];
    
    imgBtn.frame = CGRectMake(imgBtn.frame.origin.x, imgBtn.frame.origin.y,imgBtn.frame.size.width*AUTOX, imgBtn.frame.size.width*AUTOX);
    currentImg = 0;
    self.imgPaths = [NSMutableArray array];

}
- (void)closeKeyBoard
{
     [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}
- (void)setModel:(RewardModel *)model
{
    _model = model;
    titleLab.text = [NSString stringWithFormat:@"(第%@期)%@",model.reward_qishu,model.reward_title];
    if ([self.model.reward_company class] != [NSNull class] || self.model.reward_company != nil) {
        wuliuLab.text = self.model.reward_company;
    }
    if ([self.model.reward_company_code class] != [NSNull class] || self.model.reward_company_code != nil) {
        codeLab.text = self.model.reward_company_code;
    }
    if ([_model.reward_share_order_score class] != [NSNull class]  || _model.reward_share_order_score != nil) {
        if (_model!=nil && [_model.reward_share_order_score isEqualToString:@"0"]) {
            jifenLab.hidden = YES;
        }else{
            jifenLab.text = [NSString stringWithFormat:@"(额外赠送%@积分)",model.reward_share_order_score];
        }
    }
    if ([model.reward_is_virtual isEqualToString:@"0"]) {}else{
        selectBtn.hidden = YES;
        jifenLab.hidden = YES;
        yc1.hidden = YES;
        yc2.hidden = YES;
        yc3.hidden = YES;
        wuliuLab.hidden = YES;
        codeLab.hidden = YES;
        fenge.hidden = YES;
    }
    //请求默认信息
    [self requestForLasted];
}

//请求上次晒单的记录
- (void)requestForLasted
{
    [WYPublic addHudToWindow];
    NSDictionary *params = @{@"record_id":_model.reward_order_id,@"uid":[UserInfo getUserID],@"token":[UserInfo getUserToken],@"refresh_token":[UserInfo getRefreshToken]};
    [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,MOREN_URL] Parameters:params successBlock:^(NSDictionary *dic) {
        NSNumber *ret = dic[@"ret"];
        if ([ret integerValue] == 0) {
            NSDictionary *info = dic[@"data"];
            if ([info[@"sd_title"] class] != [NSNull class]) {
                titletext.text = info[@"sd_title"];
            }
            if ([info[@"sd_content"] class] != [NSNull class]) {
                descText.text = info[@"sd_content"];
            }
            if ([info[@"sd_is_show_express"] class] != [NSNull class]) {
                NSString *sflag =  info[@"sd_is_show_express"];
                if ([sflag isEqualToString:@"1"]) {
                    selectBtn.selected = YES;
                }else{
                    selectBtn.selected = NO;
                }
            }
            if ([[WYPublic getUsefullStr:info[@"sd_id"]] isEqualToString:@"0"]) {
                 selectBtn.selected = YES;
            }
            if ([info[@"sd_photolist_url"] class] != [NSNull class]) {
                NSArray *ir = info[@"sd_photolist_url"];
                NSArray *mrp = info[@"sd_photolist"];
                _morenImgs = [NSMutableArray arrayWithArray:ir];
                _morenPostPaths = [NSMutableArray arrayWithArray:mrp];
                [self getImgViewByMoren:_morenImgs];
            }
        }
        [WYPublic removeHudToWindow];
    } failedBlock:^{
        [WYPublic removeHudToWindow];
    } needLog:NO];
}
//加图片按钮
- (IBAction)imgBtnOnClick:(UIButton *)sender {
    
    if (!self.assets)
        self.assets = [[NSMutableArray alloc] init];
    
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
    //最多选几张
    picker.maximumNumberOfSelection = MAXNUM -self.imgViews.count;
    if ((MAXNUM -self.imgViews.count)<=0) {
        return;
    }
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups=NO;
    picker.delegate=self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        if ([[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo]) {
            NSTimeInterval duration = [[(ALAsset*)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
            return duration >= 5;
        } else {
            return YES;
        }
    }];
    
    [self.father presentViewController:picker animated:YES completion:NULL];
    
}


//提交
- (IBAction)commit:(id)sender {
    if(self.imgViews.count == 0){
        [WYPublic showMessageWithTitle:@"" Msg:@"请上传至少一张图片"];
        return;
    }
    oneFlag = NO;
    //添加遮罩
    [WYPublic addZheZhaoToWindowWithTitle:nil];
    //先保存图片
    for (NSInteger i = 0; i < self.assets.count; i++) {
        ALAsset *asset = self.assets[i];
        //先保存头像到本地
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"sd_%ld.jpg",(unsigned long)i]];   // 保存文件的名称
        NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage], 0.5);
        [imageData writeToFile:filePath atomically:YES];
        
    }
    //上传图片，上传成功后得到图片链接再上传晒单信息
    [self.imgPaths removeAllObjects];
    [self.imgPaths addObjectsFromArray:self.morenPostPaths];
    [self postImage];
}
/****************上传图片*****************/
- (void)postImage {
    if (titletext.text.length == 0) {
        [WYPublic showMessageWithTitle:@"" Msg:@"标题不能为空"];
        [WYPublic removeZheZhaoToWindow];
        return;
    }
    if (descText.text.length < 25) {
        [WYPublic showMessageWithTitle:@"" Msg:@"详情不能少于25字"];
        [WYPublic removeZheZhaoToWindow];
        return;
    }
    if (self.imgViews.count == 0) {
        [WYPublic showMessageWithTitle:@"" Msg:@"请选择晒单图片"];
        [WYPublic removeZheZhaoToWindow];
        return;
    }


    if (currentImg < self.assets.count) {
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
        //设置请求头
        [manager.requestSerializer setValue:[WYRequest httpHeaderFieldString] forHTTPHeaderField:@"User-Agent"];
        
        NSDictionary *parameters =@{@"uid":[UserInfo getUserID],@"token":[UserInfo getUserToken],@"refresh_token":[UserInfo getRefreshToken]};
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0]; //path数组里貌似只有一个元素
        NSString *filestr = [NSString stringWithFormat:@"/sd_%ld.jpg",(unsigned long)currentImg];
        NSString *newstr = [documentsDirectory stringByAppendingString:filestr];
        NSData *dd = [NSData dataWithContentsOfFile:newstr];
        // 加载头像
        //    userImageSupView.image = [UIImage imageWithData:dd];
        
        [manager POST:[NSString stringWithFormat:@"%@%@",DBB_IP,POST_IMG_URL] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileData:dd name:@"img" fileName:[NSString stringWithFormat:@"sd_%ld.jpg",(unsigned long)currentImg] mimeType:@"image/jpeg"];
            
        } success:^(AFHTTPRequestOperation *operation,id responseObject) {
            //请求成功的回调
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];
            NSNumber *ret = dic[@"ret"];
            if (ret.intValue == 0) {
                if ([dic[@"data"][@"img_url"] class]!=[NSNull class]) {
                    [self.imgPaths addObject:dic[@"data"][@"img"]];
                     currentImg++;
                    if(currentImg == self.imgViews.count){
                        //上传图片成功，开始上传晒单信息
                        [self postSaiDanInfo];
                        [WYPublic removeZheZhaoToWindow];
                        return;
                    }else{
                        [self postImage];
                    }
                }
            }else{
                [WYPublic showMessageWithTitle:@"图片上传失败" Msg:dic[@"msg"]];
                currentImg = 0;
                [self.imgPaths removeAllObjects];
                if(ret.intValue>2000 && ret.intValue < 3000){
                    //用户过期，强制重新登录 先删除用户信息
                    [UserInfo deleteUserInfo];
                    //登录
                    [WYPublic ifUserHaveLogin];
                }
                [WYPublic removeZheZhaoToWindow];
            }
        } failure:^(AFHTTPRequestOperation *operation,NSError *error) {
            [WYPublic showMessageWithTitle:@"" Msg:@"图片上传失败"];
            [WYPublic removeZheZhaoToWindow];
        }];

    }else{
        [self postSaiDanInfo];
        return;
    }
}
//上传晒单信息
- (void)postSaiDanInfo
{
    if (oneFlag == NO) {
        NSString *imgList = @"";
        for (NSString *img in self.imgPaths) {
            if ([imgList isEqualToString:@""]) {
                imgList = [imgList stringByAppendingString:img];
            }else{
                imgList = [imgList stringByAppendingString:[NSString stringWithFormat:@";%@",img]];
            }
        }
        NSDictionary *pararms = @{@"record_id":self.model.reward_order_id,@"title":titletext.text,@"content":descText.text,@"photolist":imgList,@"is_show_express":[NSString stringWithFormat:@"%d",selectBtn.selected],@"uid":[UserInfo getUserID],@"token":[UserInfo getUserToken],@"refresh_token":[UserInfo getRefreshToken]};
        [WYRequest startPostForDicWithUrlStR:[NSString stringWithFormat:@"%@%@",DBB_IP,POST_SAIDAN_URL] Parameters:pararms successBlock:^(NSDictionary *dic) {
            NSNumber *ret = dic[@"ret"];
            if (ret.intValue == 0) {
                //上传成功
                [WYPublic showMessageWithTitle:@"" Msg:@"晒单成功"];
                [self postSaiDanInfo];
                //跳往晒单记录
                [[WYMainTabBarVC shareMainTaBarVC].navigationController popToRootViewControllerAnimated:NO];
                NSInteger index = 2;
                NSString *show_shopping = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
                if (show_shopping.integerValue == 1) {
                    //显示
                    index = 3;
                }
                [[WYMainTabBarVC shareMainTaBarVC] changeSelectedWithIndex:index];
                ShowOrderVC *showvc = [[ShowOrderVC alloc]init];
                showvc.userId = [UserInfo getUserID];
                [[WYMainTabBarVC shareMainTaBarVC].navigationController pushViewController:showvc animated:YES];
            }else{
                [WYPublic showMessageWithTitle:@"晒单失败" Msg:dic[@"msg"]];
                if(ret.intValue>2000 && ret.intValue < 3000){
                    //用户过期，强制重新登录 先删除用户信息
                    [UserInfo deleteUserInfo];
                    //登录
                    [WYPublic ifUserHaveLogin];
                }
                
            }
            [WYPublic removeZheZhaoToWindow];
        } failedBlock:^{
            
        } needLog:NO];
    }
    oneFlag = YES;
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([descText.text isEqualToString:@"请输入25字以上内容"]) {
        descText.text = @"";
        descText.textColor = [UIColor blackColor];
    }
}
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if([descText.text isEqualToString:@""]){
        descText.text = @"请输入25字以上内容";
    }
}


//得到图片的回调方法
#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    [self.assets addObjectsFromArray:assets];
    //调整获取的图片
    [self getImgViewByChose:assets];
    [self paibanImgs];
}

- (NSArray *)indexPathOfNewlyAddedAssets:(NSArray *)assets
{
    NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
    
    for (NSInteger i = self.assets.count; i < self.assets.count + assets.count ; i++)
        [indexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
    
    return indexPaths;
}
//默认图片创建imageview
- (void)getImgViewByMoren:(NSMutableArray *)imgs
{
    //删除
    if (self.imgViews == nil) {
        self.imgViews = [NSMutableArray array];
    }
    //大小
    CGFloat s_w = imgBtn.frame.size.width;
    for (NSInteger i = 0;i<imgs.count;i++) {
        NSString *path = imgs[i];
        PostImageView *iv = [[PostImageView alloc]initWithFrame:CGRectMake(0,0,s_w,s_w)];
        UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
        longPressGr.minimumPressDuration = 1.0;
        iv.userInteractionEnabled = YES;
        iv.contentMode = UIViewContentModeScaleToFill;
        [iv addGestureRecognizer:longPressGr];
        [iv sd_setImageWithURL:[NSURL URLWithString:path] placeholderImage:[UIImage imageNamed:@"moren"]];
        iv.imgPath = path;
        iv.postPath = _morenPostPaths[i];
        iv.isDefault = YES;
        [self.imgViews addObject:iv];
    }
    [self paibanImgs];
}
//选择图片创建img
- (void)getImgViewByChose:(NSArray *)imgs
{
    //删除
    if (self.imgViews == nil) {
        self.imgViews = [NSMutableArray array];
    }
    //大小
    CGFloat s_w = imgBtn.frame.size.width;
    for (ALAsset *asset in imgs) {
        PostImageView *iv = [[PostImageView alloc]initWithFrame:CGRectMake(0,0,s_w,s_w)];
        UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
        longPressGr.minimumPressDuration = 1.0;
        iv.userInteractionEnabled = YES;
        iv.contentMode = UIViewContentModeScaleToFill;
        iv.isDefault = NO;
        [iv addGestureRecognizer:longPressGr];
        iv.image = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [self.imgViews addObject:iv];
    }

}
//排版图片
- (void)paibanImgs
{
    //删除
    if (self.imgViews.count > 0) {
        NSInteger index = 0;
        CGFloat startx = 8.0;
        CGFloat starty = 198*AUTOY;
        CGFloat add = 6*AUTOX;
        //记录相册选择图片的tag
        NSInteger choseTag = 0;
        for (NSInteger j = 0; j <self.imgViews.count ; j++) {
            //坐标x
            CGFloat o_x = startx+imgBtn.frame.size.width*index+add*index;
            //大小
            CGFloat s_w = imgBtn.frame.size.width;
            PostImageView *iv = self.imgViews[j];
            iv.frame = CGRectMake(o_x,starty,s_w,s_w);
            iv.tag = j+1;
            UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];
            longPressGr.minimumPressDuration = 1.0;
            iv.userInteractionEnabled = YES;
            [iv addGestureRecognizer:longPressGr];
            [self addSubview:iv];
            CGFloat flag = CGRectGetMaxX(iv.frame)+ add + imgBtn.frame.size.width;
            if (flag>=(WYMWITH-16)) {
                startx = 8.0;
                starty += (imgBtn.frame.size.width + add);
                index = 0;
                continue;
            }
            //如果是从相册中选择的图片为方便删除 记录
            if (!iv.isDefault) {
                iv.choseTag = choseTag;
                choseTag ++;
            }
            index++;
        }
        if (self.imgViews.count > 0) {
            //修改imgBtn的frame
            UIImageView *last = self.imgViews[self.imgViews.count - 1];
            if (CGRectGetMaxX(last.frame)+imgBtn.frame.size.width>WYMWITH) {
                imgBtn.frame = CGRectMake(8.0, last.frame.origin.y+add+imgBtn.frame.size.width, imgBtn.frame.size.width, imgBtn.frame.size.width);
            }else{
                imgBtn.frame = CGRectMake(CGRectGetMaxX(last.frame) + add, last.frame.origin.y, imgBtn.frame.size.width, imgBtn.frame.size.width);
            }
            
        }

    }
    if (self.imgViews.count == 0){
        imgBtn.frame = CGRectMake(8.0, 198*AUTOY, imgBtn.frame.size.width, imgBtn.frame.size.width);
    }
    if (self.imgViews.count >= 8) {
        imgBtn.hidden = YES;
    }else{
        imgBtn.hidden = NO;
    }
}
-(void)longPressToDo:(UILongPressGestureRecognizer *)gesture
{
    if(gesture.state == UIGestureRecognizerStateBegan)
    {
        pressedImg = (PostImageView*)gesture.view;
        UIAlertView *alt = [[UIAlertView alloc]initWithTitle:@"提示：" message:@"确认删除吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alt show];
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        if (pressedImg.tag-1 < self.imgViews.count) {
             [self.imgViews removeObjectAtIndex:pressedImg.tag-1];
            if (pressedImg.isDefault) {
                [self.morenImgs removeObject:pressedImg.imgPath];
                [self.morenPostPaths removeObject:pressedImg.postPath];
            }else{
                //如果不是默认图片 要删除选择图片
                if (pressedImg.choseTag < self.assets.count) {
                    [self.assets removeObjectAtIndex:pressedImg.choseTag];
                }
            }
            [pressedImg removeFromSuperview];
            [self paibanImgs];
        }
        
    }
}

- (IBAction)selectbtnOnclick:(UIButton *)sender {
    sender.selected = ! sender.selected;
}


@end
